using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Elvex
{
    public class ObjectUtility
    {
        public static Object Instantiate(string asset)
        {
            var obj = Assets.Load(asset);
            var go = Object.Instantiate(obj);
            return go;
        }

        public static Object Instantiate(string asset, Vector3 position, Quaternion rotation, Transform parent)
        {
            var obj = Assets.Load(asset);
            if (obj == null)
            {
                Debug.LogErrorFormat("Object({0}) Instantiate Failed.", asset);
                return null;
            }
            var go = Object.Instantiate(obj, position, rotation, parent);
            return go;
        }

        public static Object Instantiate(string asset, Vector3 position, Quaternion rotation, Transform parent, System.Type component)
        {
            var go = Instantiate(asset, position, rotation, parent) as GameObject;
            if (go != null)
            {
                if (null == go.GetComponent(component)) go.AddComponent(component);
            }
            return go;
        }

        public static Object Instantiate(string asset, Vector3 position)
        {
            return Instantiate(asset, position, Quaternion.Euler(0, 0, 0), null);
        }

        public static Object Instantiate(string asset, Vector3 position, Quaternion rotation)
        {
            var obj = Assets.Load(asset);
            if (obj == null)
            {
                Debug.LogErrorFormat("Object({0}) Instantiate Failed.", asset);
                return null;
            }
            var go = Object.Instantiate(obj, position, rotation, null);
            return go;
        }

        public static Object Instantiate(string asset, System.Type component)
        {
            var obj = Instantiate(asset);
            if(null == obj)
            {
                return obj;
            }
            var go = obj as GameObject;
            var module = go.GetComponent(component);
            if (null == module) go.AddComponent(component);
            return go;
        }


        public static T Instantiate<T>(string asset, Vector3 position, Quaternion rotation) where T : Component
        {
            var go = Instantiate(asset, position, rotation) as GameObject;
            if(null != go)
            {
                var t = go.GetComponent<T>();
                if (null == t) t = go.AddComponent<T>();
                return t;
            }
            return null;
        }
    }
}

